import { SysMenu } from '@/sys/entities/sys.entity';
import { isEmpty, sortBy, forEachRight } from 'lodash';

export type OrderTree = {
    [key: string]: any;
    orderno?: number;
    children?: OrderTree[];
};

/**
 * 依据OrderTree对象中的 orderno 进行排序
 * @param menu
 */
export function orderTree(menus: OrderTree[]): OrderTree[] {
    
    const newmenus = sortBy(menus, ['orderno']);
    newmenus.forEach((menu) => {
        if (!isEmpty(menu.children)) {
            menu.children = orderTree(menu.children);
        }
    });
    return newmenus;
}


export function filterTree(menus: SysMenu[], menuIds: number[]): SysMenu[] {
    forEachRight(menus, (menu, key) => {
        if (!menuIds.includes(menu.id)) {
            menus.splice(key, 1);
        } else {
            if (menu.children.length > 0) {
                filterTree(menu.children, menuIds);
            }
        }
    });
    return menus;
}